<?php
namespace app\common\library;
use EasyWeChat\Pay\Application;
use \Symfony\Component\HttpFoundation\Request as symfonyRequest;
class MpPay{
    public static function main(){
        $config = [
            'mch_id' => 1360656902,
            // 商户证书
            'private_key' =>root_path().'extend'.DIRECTORY_SEPARATOR. 'certs'.DIRECTORY_SEPARATOR.'apiclient_key.pem',
            'certificate' => root_path().'extend'.DIRECTORY_SEPARATOR. 'certs'.DIRECTORY_SEPARATOR.'apiclient_cert.pem',

            // v3 API 秘钥
            'secret_key' => 'xinjiangdipingxianbianminfuwu123',

            // 平台证书：微信支付 APIv3 平台证书，需要使用工具下载
            // 下载工具：https://github.com/wechatpay-apiv3/CertificateDownloader
            'platform_certs' => [
                // 如果是「微信支付公钥」模式
                //    使用Key/Value结构， key为微信支付公钥ID，value为微信支付公钥文件绝对路径
                "PUB_KEY_ID_0113606569022025082600192320002204" => root_path().'extend'.DIRECTORY_SEPARATOR. 'certs'.DIRECTORY_SEPARATOR.'pub_key.pem',
            ],

            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http' => [
                'throw'  => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
            ],
        ];
        return new Application($config);
    }
     /**
     * 获取支付参数
     */
    public static function precreate($order){
        $client = self::main()->getClient();
        $response = $client->postJson('/v3/pay/transactions/jsapi',[
                'mchid'=>'1360656902',
                'appid'=>'wxa6edd8210fc5f373',
                'description'=>$order['goods_title'],
                'out_trade_no'=>$order['out_trade_no'],
                'notify_url'=> request()->domain().'/notify.php',
                'amount' => ['total'=>intval($order['price']*100)],
                'payer' => ['openid'=>$order['openid']]
            
            ]);
        $prepay = $response->toArray(false);
        $utils = self::main()->getUtils();
        $config = $utils->buildMiniAppConfig($prepay["prepay_id"], 'wxa6edd8210fc5f373', 'RSA');
        return $config;
    }
    /**
     * 
     * 支付回调
    {
        "transaction_id":"1217752501201407033233368018",
        "amount":{
            "payer_total":100,
            "total":100,
            "currency":"CNY",
            "payer_currency":"CNY"
        },
        "mchid":"1230000109",
        "trade_state":"SUCCESS",
        "bank_type":"CMC",
        "promotion_detail":[...],
        "success_time":"2018-06-08T10:34:56+08:00",
        "payer":{
            "openid":"oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
        },
        "out_trade_no":"1217752501201407033233368018",
        "appid":"wxd678efh567hg6787",
        "trade_state_desc":"支付成功",
        "trade_type":"MICROPAY",
        "attach":"自定义数据",
        "scene_info":{
            "device_id":"013467007045764"
        }
    }*/
    public static function notify(){
        $params = request()->param();
        $request = symfonyRequest::create(
            request()->url(true),
            request()->method(),
            request()->param(),
            request()->cookie(),
            [],
            request()->server(),
            request()->getContent()?:null
        );
        self::main()->setRequestFromSymfonyRequest($request);
        $server = self::main()->getServer();
        $message = $server->getRequestMessage();
        if($message->getEventType() == 'TRANSACTION.SUCCESS'){
            return $message->toArray();
        }
        return false;
    }
    /*{
        "transaction_id":"1217752501201407033233368018",
        "amount":{
            "payer_total":100,
            "total":100,
            "currency":"CNY",
            "payer_currency":"CNY"
        },
        "mchid":"1230000109",
        "trade_state":"SUCCESS",
        "bank_type":"CMC",
        "promotion_detail":[...],
        "success_time":"2018-06-08T10:34:56+08:00",
        "payer":{
            "openid":"oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
        },
        "out_trade_no":"1217752501201407033233368018",
        "appid":"wxd678efh567hg6787",
        "trade_state_desc":"支付成功",
        "trade_type":"MICROPAY",
        "attach":"自定义数据",
        "scene_info":{
            "device_id":"013467007045764"
        }
    }*/
    public static function query($out_trade_no){
        $client = self::main()->getClient();
        $response = $client->get("/v3/pay/transactions/out-trade-no/{$out_trade_no}",['mchid'=>'1360656902']);
        if($response->getStatusCode() != 200){
            return false;
        }
        return $response->toArray(false);
        
    }

    public static function shopping($order){

        $miniApp = new \EasyWeChat\MiniApp\Application([
            'app_id' => 'wxa6edd8210fc5f373',
            'secret' => '0eecc3fcd467b61e723d9a3f0d63180e',
            'http' => [
                'throw'  => true, 
                'timeout' => 5.0,
                'retry' => true, // 使用默认重试配置
            ],
        ]);
        $accessToken = $miniApp->getAccessToken();
        $token = $accessToken->getToken();
        $client = $miniApp->getClient();
        $response = $client->postJson("/wxa/sec/order/upload_shipping_info?access_token={token}",[
            'order_key'=>[
                'order_number_type'=>1,
                'out_trade_no'=>$order['out_trade_no'],
                'mchid'=>'1360656902'
            ],
            'logistics_type'=>3,
            'delivery_mode'=>1,
            'shipping_list'=>[
               [ 'item_desc'=>$order['title']]
            ],
            'upload_time'=>''.date('Y-m-d').'T'.date('H:i:s').'.000+08:00',
            'payer'=>[
                'openid'=>$order['openid']
            ]
        ]);
        return $response->toArray();
    }
}